#import "PlayerNamesViewController.h"
#import "RoundsViewController.h"
#import "GamesToPlayTableViewController.h"
#import "Settings.h"
#import "constants.h"

@interface PlayerNamesViewController ()
@property (weak, nonatomic) IBOutlet UILabel *playerTwoLabelToRotate;
@property (weak, nonatomic) IBOutlet UITextField *playerTwoFieldToRotate;
@property (weak, nonatomic) IBOutlet UITextField *playerOneField;

@property BOOL playerOneReady;
@property BOOL playerTwoReady;

@property BOOL resumed;
@property (weak, nonatomic) IBOutlet UIButton *playerTwoStartButton;
@property (weak, nonatomic) IBOutlet UIButton *playerOneStartButton;
@property (strong, nonatomic) IBOutlet UILabel *timerLabel;

@property Settings *settings;
@property BOOL keyboardShown;

@end

@implementation PlayerNamesViewController

//start game with timer
-(void)startGame {
    
    //check if any games are selcted
    if ([self.settings.gamesToPlay count] > 0) {
        self.resumed = NO;
        for (UIView *subView in self.view.subviews ) {
            subView.alpha = 0.5;
        }
        self.timerLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 300, 350, 350)];
        self.timerLabel.textColor = [UIColor whiteColor];
        [self.timerLabel setFont:[UIFont systemFontOfSize:200]];
        self.timerLabel.alpha = 1;
        self.timerLabel.text = @"III";
        self.timerLabel.textAlignment = NSTextAlignmentCenter;
        self.timerLabel.hidden= NO;
        [self.view addSubview:self.timerLabel];
        [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(onTick:)
                                       userInfo:nil
                                        repeats:YES];
        
        
        
        
    }
    //selct games!
    else {
        self.resumed = YES;
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Unable to start game"
                                                          message:@"No games selcted"
                                                         delegate:self
                                                cancelButtonTitle:nil                                                otherButtonTitles:@"Settings", nil];
        
        [message show];
    }
    
}
//countdown timer
-(void)onTick:(NSTimer *)timer {
    static int countdown = 2;
    
    if (countdown == 0) {
        [timer invalidate];
        countdown = 2;
        RoundsViewController *rVC = [[RoundsViewController alloc] init];
        playerOneName=self.playerOneField.text;
        playerTwoName=self.playerTwoFieldToRotate.text;
        [self.navigationController pushViewController:rVC animated:YES];
        
    }
    self.timerLabel.text = [self.timerLabel.text substringFromIndex:1];
    countdown--;
    
    
}
//player two ready
- (IBAction)playerTwoStartButtonClicked:(id)sender {
    
    if (![self.playerTwoFieldToRotate.text isEqualToString:@""])
    {
        self.playerTwoReady =YES;
        
        [self.playerTwoStartButton setTitleColor:[UIColor colorWithRed:0 green:1 blue:0 alpha:0.5] forState:UIControlStateNormal];;
        
        if (self.playerTwoReady && self.playerOneReady) {
            [self.playerTwoFieldToRotate resignFirstResponder];
            [self.playerOneField resignFirstResponder];
            [self startGame];
        }
    }
    
}
//player one ready
- (IBAction)playerOneStartButtonClicked:(id)sender {
    
    if (![self.playerOneField.text isEqualToString:@""])
    {
        self.playerOneReady =YES;
        
        [self.playerOneStartButton setTitleColor:[UIColor colorWithRed:0 green:1 blue:0 alpha:0.5] forState:UIControlStateNormal];;
        
        if (self.playerTwoReady && self.playerOneReady) {
            [self.playerTwoFieldToRotate resignFirstResponder];
            [self.playerOneField resignFirstResponder];
            
            [self startGame];
        }
    }
    
}
//go to settings if ALERT
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    
    if([title isEqualToString:@"Settings"])
    {
        GamesToPlayTableViewController *selectGamesVC = [[GamesToPlayTableViewController alloc] init];
        [self.navigationController pushViewController:selectGamesVC animated:YES];
    }
}

- (IBAction)playerOne:(id)sender {
    if (self.keyboardShown) {
        UIView *keyb = [self getKeyboard];
        keyb.transform = CGAffineTransformMakeRotation(2 * M_PI);
        CGRect screenRect = [[UIScreen mainScreen] bounds];
        kScreenHeight = screenRect.size.height;
        keyb.frame = CGRectMake(0, kScreenHeight - keyb.frame.size.height, keyb.frame.size.width, keyb.frame.size.height);
    }
    else {
        [NSTimer scheduledTimerWithTimeInterval:0.1
                                         target:self
                                       selector:@selector(playerOne:)
                                       userInfo:nil
                                        repeats:NO];
    }
}
- (IBAction)playerTwo:(id)sender {
    
    if (self.keyboardShown) {
        UIView *keyb = [self getKeyboard];
        keyb.transform = CGAffineTransformMakeRotation(M_PI);
        keyb.frame = CGRectMake(0, 0, keyb.frame.size.width, keyb.frame.size.height);
        
    }
    else {
        
        [NSTimer scheduledTimerWithTimeInterval:0.1
                                         target:self
                                       selector:@selector(playerTwo:)
                                       userInfo:nil
                                        repeats:NO];
    }
}


- (UIView*)getKeyboard
{
    UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:2];
    UIView* keyboard;
    
    for(int i = 0 ; i < [tempWindow.subviews count] ; i++)
    {
        keyboard = [tempWindow.subviews objectAtIndex:i];
        if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES){
            return keyboard;        }
        else if([[keyboard description] hasPrefix:@"<UIInputSetContainerView"] == YES){
            return keyboard;
        }
    }
    return keyboard;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.settings = [Settings sharedSettings];
    self.playerOneReady = NO;
    self.playerTwoReady = NO;
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES];
    self.playerTwoFieldToRotate.transform = CGAffineTransformMakeRotation(M_PI);
    self.playerTwoLabelToRotate.transform = CGAffineTransformMakeRotation(M_PI);
    self.playerTwoStartButton.transform = CGAffineTransformMakeRotation(M_PI);
    
    
    self.playerOneField.delegate = self;
    self.playerTwoFieldToRotate.delegate = self;
    
    self.playerOneField.keyboardAppearance = UIKeyboardAppearanceDark;
    self.playerTwoFieldToRotate.keyboardAppearance = UIKeyboardAppearanceDark;
    
}
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}
-(void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    //keyboard notifications
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardDidHideNotification object:nil];
    [self.navigationController setNavigationBarHidden:YES];
    if (self.resumed) {
        self.timerLabel.alpha = 1;
        [self startGame];
    }
    
}
-(void)keyboardShown:(NSNotification*) notification {
    self.keyboardShown = YES;
}
-(void)keyboardHidden:(NSNotification*) notification {
    self.keyboardShown = NO;
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(BOOL)prefersStatusBarHidden
{ return YES;
}
@end
